iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 8

day-8[medium.2012]sum of beauty in the array

  • 分享至 

  • xImage
  •  

You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals:

2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <= nums.length - 1.
1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not satisfied.
0, if none of the previous conditions holds.
Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.


  • previous=前者的
  • condition=狀態
    題目大意要我們按照規則去賦予矩陣中的每個(除了頭尾)元素「美麗度」,最後加總返回。
    美麗度2分:左邊所有值都小於i;右邊所有值都大於i
    美麗度1分:左邊一格值小於i;右邊一格值大於i,且不滿足2分條件
    美麗度0分:上面兩個條件都不滿足

我的初步解題思路是

  1. 先遍歷每個元素,
  2. 判斷後把美麗度存到一個新矩陣,
  3. 最後再加總。
    雖然實際開始寫程式的時候我發現判斷的那個步驟會很冗長就是了:P

public class Solution {
public int sumOfBeauties(int[] nums) {
int n = nums.length;
// 存儲每個元素美麗度的矩陣
int[] beauty = new int[n];
// 遍歷判斷每個元素的美麗度
for (int i = 1; i <= n - 2; i++) {
boolean leftSmaller = true; // 判斷左邊是否所有元素都小於i值
boolean rightBigger = true; // 判斷右邊是否所有元素都大於i值
// 檢查左邊的所有元素
for (int j = 0; j < i; j++) {
if (nums[j] >= nums[i]) {
leftSmaller = false;
break;
}
}
// 檢查右邊的所有元素
for (int k = i + 1; k < n; k++) {
if (nums[k] <= nums[i]) {
rightBigger = false;
break;
}
}
// 美麗度2分
if (leftSmaller && rightBigger) {
beauty[i] = 2;
}
// 美麗度1分
else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
beauty[i] = 1;
}
}
// 加總美麗度數組
int beautySum = 0;
for (int i = 1; i <= n - 2; i++) {
beautySum += beauty[i];
}
return beautySum;
}
}


丟去leetcode看結果!
雖然成功了,但感覺我的方法有點暴力...
不過因為是第一次嘗試中等難度,我想應該有寫出來就算合格了:D
https://ithelp.ithome.com.tw/upload/images/20240922/20169432DBMtfORaqy.png


上一篇
day-7[easy.1952]three divisors
下一篇
day-9[medium.2048]next greater numerically balanced number
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言